package com.atguigu.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQConfig
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-26
 * @Description:
 */
@Configuration
@ComponentScan({"com"})
public class RabbitMQConfig {
    /**
     * 创建连接工厂
     */
    @Bean
    public ConnectionFactory connectionFactory(){
        // 设置数据源
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses("localhost:5672");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        return  connectionFactory;
    }

    /**
     * 创建RabbitAdmin
     * 作用：创建交换机，创建队列，绑定交换机和队列
     */
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 如果使用spring必须设置当前参数,如果不设置这个参数spring容器不会加载rabbitAdmin
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }
}